package com.atguigu.sparkstreaming.getoffsets

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Created by Smexy on 2022/8/22
 *
 *
 *    演示获取offsets可能会犯的错误
 *
 * Exception in thread "main" java.lang.ClassCastException:
 *      org.apache.spark.rdd.MapPartitionsRDD
 *          cannot be cast to
 *      org.apache.spark.streaming.kafka010.HasOffsetRanges
 *
 *      MapPartitionsRDD 无法转换为 HasOffsetRanges 类型
 *
 *       rdd.asInstanceOf[HasOffsetRanges].offsetRanges
 *
 *
 *       HasOffsetRanges 只有一个子类:  KafkaRDD
 *        只有当rdd是 KafkaRDD 类型时，此行代码才不会报错！
 *
 *        结论： 只有初始DS，其中封装的RDD才是kafkaRDD
 */
object GetOffsetsDemo4 {

  def main(args: Array[String]): Unit = {


    val streamingContext = new StreamingContext("local[*]", "wordcount", Seconds(5))

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "hadoop102:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "sz220409test",
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> "true"
    )


    val topics = Array("topicD")


    // 初始DS
    val ds: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      streamingContext,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    //先做了map操作，map也没做处理
    val ds1: DStream[ConsumerRecord[String, String]] = ds.map(record => record)

    ds.foreachRDD(rdd => {


      val ranges: Array[OffsetRange] = rdd.asInstanceOf[HasOffsetRanges].offsetRanges


      for (offsetRange <- ranges) {
        println(Thread.currentThread().getName + "当前消费了:" + offsetRange.topic + "  主题的"
          + offsetRange.partition + "  分区，从"
          + offsetRange.fromOffset + " 消费到了 " + offsetRange.untilOffset)
      }

      rdd.foreach(record => println(Thread.currentThread().getName + record.value()));

    })


    streamingContext.start()

    streamingContext.awaitTermination()

  }

}
